<template>
  <div class="package-edit-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>套餐编辑</span>
          <el-button type="primary" @click="handleSubmit">保存套餐</el-button>
        </div>
      </template>

      <el-form ref="saleMealFormRef" :model="saleMealEdit" :rules="rules" label-position="top">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="saleMealEdit.name" placeholder="请输入套餐名称"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="saleMealEdit.price"
            :precision="2"
            :step="1"
            :min="1"
            style="width: 200px"
          >
            <template #prefix>
              <span>￥</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="套餐描述" prop="remark">
          <el-input
            v-model="saleMealEdit.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入套餐描述"
          ></el-input>
        </el-form-item>

        <EditTable
          :ref="(el) => setTableRef(el, 'MAIN')"
          title="主材清单"
          :data="oriMaterialsMap['MAIN']"
          @add-window="showMaterialWindow('MAIN')"
        />

        <EditTable
          :ref="(el) => setTableRef(el, 'SUB')"
          title="辅材清单"
          :data="oriMaterialsMap['SUB']"
          @add-window="showMaterialWindow('SUB')"
        />

        <EditTable
          :ref="(el) => setTableRef(el, 'NORM')"
          title="定额清单"
          :data="oriMaterialsMap['NORM']"
          @add-window="showMaterialWindow('NORM')"
        />
      </el-form>
    </el-card>

    <!-- 客户表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="900px"
      @close="closeMaterialWindow"
    >
      <!-- 材料表格 -->
      <MaterialSelector
        v-if="dialog.visible && materialType != 'NORM'"
        ref="materialRef"
        :type="materialType"
      />
      <!-- 定额表格 -->
      <NormSelector v-if="dialog.visible && materialType == 'NORM'" ref="normRef" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="chooseMaterialDone">确 定</el-button>
          <el-button @click="closeMaterialWindow">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import MaterialSelector from "@/views/business/material/material/MaterialSelector.vue";
import SealMealAPI, {
  SaleMealTypeLabel,
  SealMealForm,
  SealMealItem,
} from "@/api/business/material/sealMeal.api";
import NormSelector from "@/views/business/material/norm/components/NormSelector.vue";
import EditTable from "./edit-table.vue";
import { toMapList } from "@/utils";

defineOptions({
  name: "SaleMealItem",
  inheritAttrs: false,
});

const route = useRoute();

const saleMealId = ref("");
const materialRef = ref();
const normRef = ref();
const saleMealFormRef = ref();
const saleMealEdit = reactive<SealMealForm>({
  price: 0,
  items: [],
});

const dialog = reactive({
  title: "",
  visible: false,
});

const materialType = ref("MAIN");
const oriMaterialsMap = ref<{ [key: string]: SealMealItem[] }>({}); //原始材料数据包

const tableRefs = ref<{ [key: string]: any }>({});
const setTableRef = (el: any, type: string) => {
  if (el) {
    tableRefs.value[type] = el;
  }
};

onActivated(() => {
  if (route.query.saleMealId == saleMealId.value) return;
  // id变动 重置数据
  saleMealId.value = route.query.saleMealId as string;
  loadSaleMealDetail();
});

const loadSaleMealDetail = () => {
  if (!saleMealId.value || saleMealId.value == "0") {
    return;
  }
  SealMealAPI.getFormData(saleMealId.value).then((data) => {
    Object.assign(saleMealEdit, data, { price: parseFloat((data.price as string) || "0") });
    if (!data.items) {
      return;
    }
    oriMaterialsMap.value = toMapList(data.items, "type");
  });
};

/**
 * 确认添加
 */
const chooseMaterialDone = () => {
  try {
    let curList: any[] =
      materialType.value === "NORM" ? normRef.value.getChecked() : materialRef.value.getChecked();
    if (!curList || curList.length === 0) return;
    const addList = curList.map(({ id, name, price, costPrice, unit, spec, code }) => ({
      resourceId: id,
      name,
      type: materialType.value,
      price,
      costPrice: costPrice || price,
      num: 1,
      unit,
      spec,
      code,
    }));
    tableRefs.value[materialType.value].addMaterial(addList);
  } catch (error) {
    ElMessage.error("添加失败");
    console.error("添加失败", error);
  } finally {
    dialog.visible = false;
  }
};

/**
 * 打开添加弹窗
 * @param type
 */
function showMaterialWindow(type: string) {
  materialType.value = type;
  dialog.visible = true;
  dialog.title = "添加" + SaleMealTypeLabel[type];
  nextTick(() => {
    type === "NORM" ? normRef.value.handleQuery() : materialRef.value.handleQuery();
  });
}

/**
 * 关闭添加弹窗
 */
function closeMaterialWindow() {
  dialog.visible = false;
}

const handleSubmit = async () => {
  saleMealFormRef.value.validate((valid: any) => {
    let itemList: any[] = [];
    ["MAIN", "SUB", "NORM"].forEach((str) => {
      const ls = tableRefs.value[str].getData();
      itemList = [...itemList, ...ls];
    });
    saleMealEdit.items = itemList;
    if (valid) {
      const id = saleMealEdit.id;
      if (id) {
        SealMealAPI.update(saleMealEdit).then(() => {
          ElMessage.success("修改成功");
        });
      } else {
        SealMealAPI.create(saleMealEdit).then((data) => {
          saleMealEdit.id = data.id;
          ElMessage.success("新增成功");
        });
      }
    }
  });
};

const rules = reactive({
  name: [{ required: true, message: "请输入套餐名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入套餐价格", trigger: "blur" }],
  remark: [{ required: true, message: "请输入套餐描述", trigger: "blur" }],
});
</script>

<style scoped>
.package-edit-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
